#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
部署检查脚本
验证WMS Sample系统在不同部署环境下的完整性
"""

import sys
import os
import sqlite3
from pathlib import Path

# 添加项目根目录到Python路径
current_dir = Path(__file__).parent.parent
sys.path.insert(0, str(current_dir))

from src.core.path_manager import path_manager
from src.core.config import config

def check_deployment():
    """检查部署完整性"""
    print("========================================")
    print("WMS Sample 部署完整性检查")
    print("========================================")
    print()
    
    # 基本信息
    print("基本信息:")
    print(f"  部署模式: {path_manager.deployment_mode}")
    print(f"  Python版本: {sys.version}")
    print(f"  工作目录: {Path.cwd()}")
    print(f"  应用目录: {path_manager.app_dir}")
    print()
    
    # 检查关键目录
    print("目录检查:")
    directories = [
        ("应用目录", path_manager.app_dir),
        ("数据目录", path_manager.data_dir),
        ("配置目录", path_manager.config_dir),
        ("日志目录", path_manager.logs_dir),
        ("src目录", path_manager.app_dir / "src"),
        ("API目录", path_manager.app_dir / "src" / "api"),
        ("模型目录", path_manager.app_dir / "src" / "models"),
        ("核心目录", path_manager.app_dir / "src" / "core"),
    ]
    
    all_dirs_ok = True
    for name, dir_path in directories:
        exists = dir_path.exists()
        print(f"  {name}: {'✅' if exists else '❌'} ({dir_path})")
        if not exists:
            all_dirs_ok = False
    print()
    
    # 检查关键文件
    print("关键文件检查:")
    key_files = [
        ("主程序", path_manager.app_dir / "main_new.py"),
        ("服务脚本", path_manager.app_dir / "wms_service.py"),
        ("客户端", path_manager.app_dir / "client_gui.py"),
        ("配置文件", path_manager.get_config_file()),
        ("路径管理器", path_manager.app_dir / "src" / "core" / "path_manager.py"),
        ("配置管理器", path_manager.app_dir / "src" / "core" / "config.py"),
        ("数据库模型", path_manager.app_dir / "src" / "models" / "database" / "models.py"),
        ("数据库管理", path_manager.app_dir / "src" / "models" / "database" / "database.py"),
        ("API服务器", path_manager.app_dir / "src" / "api" / "api_server.py"),
        ("服务管理器", path_manager.app_dir / "src" / "core" / "service_manager.py"),
    ]
    
    all_files_ok = True
    for name, file_path in key_files:
        exists = file_path.exists()
        print(f"  {name}: {'✅' if exists else '❌'} ({file_path})")
        if not exists:
            all_files_ok = False
    print()
    
    # 检查配置
    print("配置检查:")
    try:
        print(f"  API主机: {config.api_host}")
        print(f"  API端口: {config.api_port}")
        print(f"  数据库路径: {config.database_path}")
        config_ok = True
    except Exception as e:
        print(f"  ❌ 配置加载失败: {e}")
        config_ok = False
    print()
    
    # 检查数据库
    print("数据库检查:")
    db_path = Path(config.database_path)
    if db_path.exists():
        try:
            conn = sqlite3.connect(str(db_path))
            cursor = conn.cursor()
            
            # 检查表结构
            cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
            tables = [row[0] for row in cursor.fetchall()]
            
            expected_tables = ['plates', 'positions']
            tables_ok = all(table in tables for table in expected_tables)
            
            print(f"  数据库文件: ✅ ({db_path})")
            print(f"  数据库表: {'✅' if tables_ok else '❌'} ({', '.join(tables)})")
            
            # 检查任务追踪字段
            cursor.execute("PRAGMA table_info(positions)")
            columns = [column[1] for column in cursor.fetchall()]
            
            task_fields = ['task_id', 'task_type', 'operator', 'operation_time']
            task_fields_ok = all(field in columns for field in task_fields)
            
            print(f"  任务追踪字段: {'✅' if task_fields_ok else '❌'}")
            
            conn.close()
            db_ok = tables_ok and task_fields_ok
            
        except Exception as e:
            print(f"  ❌ 数据库检查失败: {e}")
            db_ok = False
    else:
        print(f"  ❌ 数据库文件不存在: {db_path}")
        db_ok = False
    print()
    
    # 检查Python依赖
    print("Python依赖检查:")
    required_packages = [
        'tkinter',
        'requests', 
        'fastapi',
        'uvicorn',
        'sqlalchemy',
        'pydantic'
    ]
    
    deps_ok = True
    for package in required_packages:
        try:
            __import__(package)
            print(f"  {package}: ✅")
        except ImportError:
            print(f"  {package}: ❌")
            deps_ok = False
    print()
    
    # 检查可选依赖（Windows服务相关）
    print("可选依赖检查:")
    optional_packages = [
        'win32serviceutil',
        'win32service', 
        'win32event',
        'servicemanager'
    ]
    
    for package in optional_packages:
        try:
            __import__(package)
            print(f"  {package}: ✅")
        except ImportError:
            print(f"  {package}: ❌ (Windows服务功能不可用)")
    print()
    
    # 总结
    print("========================================")
    print("检查结果总结")
    print("========================================")
    
    checks = [
        ("目录结构", all_dirs_ok),
        ("关键文件", all_files_ok),
        ("配置文件", config_ok),
        ("数据库", db_ok),
        ("Python依赖", deps_ok)
    ]
    
    all_ok = True
    for name, status in checks:
        print(f"  {name}: {'✅ 通过' if status else '❌ 失败'}")
        if not status:
            all_ok = False
    
    print()
    if all_ok:
        print("🎉 部署检查全部通过！系统可以正常运行。")
    else:
        print("⚠️  部署检查发现问题，请修复后再运行系统。")
    
    print("========================================")
    
    return all_ok

def check_import_paths():
    """检查导入路径"""
    print("导入路径检查:")
    
    try:
        from src.core.path_manager import path_manager
        print("  path_manager: ✅")
    except ImportError as e:
        print(f"  path_manager: ❌ {e}")
    
    try:
        from src.core.config import config
        print("  config: ✅")
    except ImportError as e:
        print(f"  config: ❌ {e}")
    
    try:
        from src.models.database.database import db_manager
        print("  db_manager: ✅")
    except ImportError as e:
        print(f"  db_manager: ❌ {e}")
    
    try:
        from src.api.api_server import app
        print("  api_server: ✅")
    except ImportError as e:
        print(f"  api_server: ❌ {e}")
    
    print()

if __name__ == "__main__":
    check_import_paths()
    success = check_deployment()
    sys.exit(0 if success else 1) 